import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
import _ from 'lodash';
import routes from './routes'
import {setPageTitle} from '../common/utils.js'
import { $nprogress, $utils, $menuUtils } from '@jzl/utils'
import {useCommonStore, useMultiTagsStore} from "@jzl/stores";
import Demo from '../views/demo.vue'
import {COMMON_LAYOUT_ROUTE, COMMON_PAGE_ROUTES, getCommonPageRoutes, Page404} from "@jzl/comps";
import {defineAsyncComponent, resolveComponent} from "vue";

COMMON_LAYOUT_ROUTE.children = COMMON_LAYOUT_ROUTE.children.concat(routes)

// console.log(import.meta.env.BASE_URL, import.meta.env.VITE_CLIENT_TYPE)

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_URL),
  linkActiveClass: 'active',
  routes: [
    {
      path: '/login',
      name: 'login',
      meta: {
        title: "登录"
      },
      // component: () => import('../views/login.vue')
      component: defineAsyncComponent(() =>
        Promise.resolve({ template: '<Login />' })
      )
    },
    {
      path: '/:appType(app|appid)-:appValue/login',
      name: 'AppLogin',
      component: defineAsyncComponent(() =>
        Promise.resolve({ template: '<Login />' })
      )
    },
    COMMON_LAYOUT_ROUTE,
    {
      path: '/',
      name: 'index',
      meta: {
        title: "工作台"
      },
      // redirect: '/home',
      component: () => import('../views/workspace/layout.vue'),
      children: [{
        path: 'home',
        name: 'home',
        meta: {
          title: "门户"
        },
        component: () => import('../views/home.vue')
      }, {
        path: 'apps',
        name: 'apps',
        meta: {
          title: "应用中心"
        },
        component: () => import('../views/demo.vue')
      }, ...getCommonPageRoutes('WorkSpace')
      ]
    },
    {
      path: '/demo',
      name: 'demo',
      meta: {
        title: "DEMO"
      },
      component: () => import('../views/demo.vue')
    },
    {
      path: '/bg',
      name: 'bg',
      meta: {
        title: "BG"
      },
      component: () => import('../views/bg.vue')
    },
    {
      path: '/demo-rule',
      name: 'demo-rule',
      meta: {
        title: "DEMO"
      },
      component: () => import('../views/demo-rule.vue')
    },
    {
      path: '/demo-form',
      name: 'demo-form',
      meta: {
        title: "DEMO"
      },
      component: () => import('../views/demo-form.vue')
    },
    {
      path: '/form',
      name: 'form',
      component: () => import('../views/form.vue')
    },
    {
      path: '/404',
      name: '404',
      component: Page404
    },
    /*{
    // path: '/',
    path: '/:appType-:appValue',
    name: 'Layout',
    component: () => import('../views/layout.vue'),
    children: routes // routes.concat(v)
  }, */
  ],
  scrollBehavior(to, from, savedPosition) {
    return {top: 0}; // 总是滚动到顶部
  }
});

// router.options.routes[0].children.push(v);

/*for(let i = 1; i <= 4; i++) {
  let v = {
    name: 'demo-' + i,
    path: "/demo-" + i,
    component: Demo
  };
  router.addRoute('Layout', v);
}*/
/*
router.addRoute('Layout', {
  name: 'pc-pc-002',
  path: '/pc-pc-002',
  component: Demo
});*/
// let flattenRouters = router.getRoutes()
// router.addRoute(flattenRouters);

router.beforeEach(async (to, _from, next) => {

  const store = useCommonStore();

  setPageTitle(to?.meta?.title);

  const userInfo = store.loginUser;
  $nprogress.start();
// console.log(userInfo, store.menusRoot, to.fullPath, _.isEmpty(userInfo))
  if (!_.isEmpty(userInfo) && !store.menusRoot) {
    /*let appType = to.params?.appType;
    let appValue = to.params?.appValue;
    let appCode = '';
    let appId = '';
    if(appType === 'appid') {
      appId = appValue;
    } else if(appType === 'app') {
      appCode = appValue;
    }
    // console.log(to)
    let menus = await store.initMenus(appCode, appId);*/

    /*await $utils.traverseTree(menus, (menu) => {
      if(_.startsWith(menu?.path, '/pc-')) {
        return;
      }
      router.addRoute('Layout', {
        name: menu?.path,
        path: menu?.path,
        meta: menu?.meta,
        component: Demo
      });
    }, 'subs');*/

    // store.init
    // 无权限跳转403页面
    // if (to.meta?.roles && !isOneOfArray(to.meta?.roles, userInfo?.roles)) {
    //   next({path: "/error/403"});
    // }
    /*if (_from?.name) {
      // name为超链接
      toCorrectRoute();
    } else {
      // 刷新
      if (!store.menus) {
        initRouter().then((router: Router) => {
          if (!useMultiTagsStoreHook().getMultiTagsCache) {
            const {path} = to;
            const route = findRouteByPath(
              path,
              router.options.routes[0].children
            );
            getTopMenu(true);
            // query、params模式路由传参数的标签页不在此处处理
            if (route && route.meta?.title) {
              if (isAllEmpty(route.parentId) && route.meta?.backstage) {
                // 此处为动态顶级路由（目录）
                // const { path, name, meta } = route.children[0];
                let xRouter = route?.children?.[0];
                if (!xRouter) xRouter = route;
                const {path, name, meta} = xRouter;// route?.children[0];
                useMultiTagsStoreHook().handleTags("push", {
                  path,
                  name,
                  meta
                });
              } else {
                const {path, name, meta} = route;
                useMultiTagsStoreHook().handleTags("push", {
                  path,
                  name,
                  meta
                });
              }
            }
          }
          // 确保动态路由完全加入路由列表并且不影响静态路由（注意：动态路由刷新时router.beforeEach可能会触发两次，第一次触发动态路由还未完全添加，第二次动态路由才完全添加到路由列表，如果需要在router.beforeEach做一些判断可以在to.name存在的条件下去判断，这样就只会触发一次）
          if (isAllEmpty(to.name)) router.push(to.fullPath);
        });
      }
      toCorrectRoute();
    }*/
    await next();
  } else {
    let menus = store.menus;

    /*if (!useMultiTagsStore().getMultiTagsCache) {
      const {path} = to;
      const route = $utils.getTreeDataFn(menus, (menu) => {
        return path === $menuUtils.getMenuRouterPath(menu, to);
      },
        'subs'
      );

      // console.log('============>>>>>>')
      // console.log(route)
      // getTopMenu(true);
      // query、params模式路由传参数的标签页不在此处处理
      if (route && route.meta?.title) {
        const {name, meta} = route;
        useMultiTagsStore().handleTags("push", {
          path,
          name,
          meta
        });
      }
    }*/

    await next();
  }
  $nprogress.done();
});

export default router
